package cn.microservices.cloud.system.service.manger;

import cn.microservices.cloud.common.core.utils.SoMap;
import cn.microservices.cloud.common.web.utils.CommonRequestUtils;
import cn.microservices.cloud.system.api.bo.EmployeeBO;
import cn.microservices.cloud.system.api.bo.UserInfoBO;
import cn.microservices.cloud.system.api.dto.LoginDTO;
import cn.microservices.cloud.system.api.dto.RegisterDTO;
import cn.microservices.cloud.system.api.service.AuthService;
import cn.microservices.cloud.system.api.vo.RegisterVO;
import cn.microservices.cloud.system.api.vo.UserInfoVO;
import cn.microservices.cloud.system.service.convert.AuthConvert;
import com.ejlchina.okhttps.OkHttps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class AuthManager {
    @Resource
    private AuthService authService;

    @Value("${auth.login.url}")
    public String authLoginUrl;
    @Value("${microservices.header.from}")
    public String from;
    /**
     * 注册
     * @param registerDTO
     * @return
     */
    public RegisterVO register(RegisterDTO registerDTO) {
        EmployeeBO employeeBO = authService.register(registerDTO);
        return AuthConvert.INSTANCE.convertBO(employeeBO);
    }


    /**
     * 登录
     * @param loginDTO
     * @param response
     * @param request
     * @return
     */
    public UserInfoVO login(LoginDTO loginDTO, HttpServletResponse response, HttpServletRequest request) {
        UserInfoBO userInfoBO = authService.findUserInfo(loginDTO);
        if (StringUtils.isEmpty(userInfoBO.getClientId())){
            userInfoBO.setClientId(userInfoBO.getUsername().substring(0,4));
        }
        String str = OkHttps.sync(authLoginUrl + "/oauth2/token")
                .addBodyPara("grant_type", "password")
                .addBodyPara("client_id", loginDTO.getUsername())
//                .addBodyPara("client_id", 1001)
                .addBodyPara("username", loginDTO.getUsername())
                .addBodyPara("password", loginDTO.getPassword())
                .addBodyPara("loginType", loginDTO.getIdentityType())
                .addHeader("equipmentType", CommonRequestUtils.getDevice())
                .addHeader("from",from)
                .post()
                .getBody()
                .toString();
        SoMap so = SoMap.getSoMap().setJsonString(str);
//        response.addHeader("token",so.getString(""));
        return AuthConvert.INSTANCE.convert(new EmployeeBO());
    }
}
